from . import models

from app_common import app_except


def accumulated_sale_count_of_goods(shopping: models.StoreShopping) -> None:
    if not shopping.state == models.StoreShopping.ShoppingState.PAID.value:
        return
    shopping_content_s = models.StoreShoppingContent.objects.filter(
        deleted=False
    ).filter(shopping_uuid=shopping.uuid)
    if not shopping_content_s:
        raise app_except.NullErr(msg=f"购物商品为空: {shopping.uuid}")
    bulk_update_goods = []
    for content in shopping_content_s:
        good = (
            models.StoreGood.objects.filter(deleted=False)
            .filter(uuid=content.good_uuid)
            .first()
        )
        good.total_sale_count += content.pay_count

        bulk_update_goods.append(good)
    models.StoreGood.objects.bulk_update(bulk_update_goods, fields=["total_sale_count"])
